package com.soup.commons;

import com.soup.commons.exception.GeneratorException;

import java.awt.*;

public class ColorGenerator {

    /**
     * 16 进制颜色转 Color
     * @param color
     * @return
     * @throws GeneratorException
     */
    public final Color generator(String color) throws GeneratorException{
        if (color.startsWith("#")) {
            String ops = color.substring(1).toLowerCase();
            if (ops.length() == 6) {
                return new Color(Integer.parseInt(ops,16));
            } else if (ops.length() == 3){
                ops = ops.charAt(0) + "" + ops.charAt(0) +
                        ops.charAt(1) + "" + ops.charAt(1) +
                        ops.charAt(2) + "" + ops.charAt(2);
                return new Color(Integer.parseInt(ops,16));
            } else {
                throw new GeneratorException("16进制颜色格式不正确");
            }
        } else {
            throw new GeneratorException("16进制颜色必须以#开头");
        }
    }

    /**
     * 颜色转 16进制 字符串
     * @param color
     * @return
     */
    public final String generator(Color color){
        String R = Integer.toHexString(color.getRed());
        String B = Integer.toHexString(color.getBlue());
        String G = Integer.toHexString(color.getGreen());
        R = R.length() < 2 ? ('0' + R) : R;
        B = B.length() < 2 ? ('0' + B) : B;
        G = G.length() < 2 ? ('0' + G) : G;
        return '#' + R + B + G;
    }

}
